package com.xiaocz.hblsubstitutedriving;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.widget.AppCompatImageView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.hedan.textdrawablelibrary.TextViewDrawable;
import com.vise.log.ViseLog;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.widgets.dialog.LoadingDialog;
import com.xiaocz.hblsubstitutedriving.activities.activity.OrderCourseActivity;
import com.xiaocz.hblsubstitutedriving.activities.activity.VipActivity;
import com.xiaocz.hblsubstitutedriving.model.CloudOrder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * Time:2020/5/28
 * Created by xiaocz
 * Describe 云订单-提示框
 */
public class FTService extends Service {

    View mFloatLayout;
    Button okOrder;
    TextView tv_distance;
    WindowManager mWindowManager;
    WindowManager.LayoutParams wmParams;
    TextViewDrawable tvStartAddress;
    TextViewDrawable tvEndAddress;

    /**
     * 接单倒计时
     */
    private OrderCountDownTimer orderCountDownTimer;
    private CloudOrder cloudOrder;

    private void init() {
        this.wmParams = new WindowManager.LayoutParams();
        this.mWindowManager = ((WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        DisplayMetrics dm = new DisplayMetrics();
        this.wmParams.x = (int) (dm.widthPixels * 0.88); //设置宽度
        this.wmParams.flags = 8;
        this.wmParams.gravity = Gravity.TOP | Gravity.CENTER;
        this.wmParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        this.wmParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        this.wmParams.alpha = 2.0F;
        this.mFloatLayout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.sevice_dialog, null);
        TextView right_btn = mFloatLayout.findViewById(R.id.right_btn);
        this.tv_distance=mFloatLayout.findViewById(R.id.tv_distance);
        this.okOrder = mFloatLayout.findViewById(R.id.btn_take_order);
        tvStartAddress = mFloatLayout.findViewById(R.id.tv_start_address);
        tvEndAddress = mFloatLayout.findViewById(R.id.tv_end_address);
        this.mWindowManager.addView(this.mFloatLayout, this.wmParams);
        right_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cloudOrder != null) {
                    webOrderStop(cloudOrder.getOrderNo());//拒单会降低自己的派单率、接单率，平台有权进行处罚。选择按钮：仍然拒绝、不拒绝
                }
            }
        });
        this.okOrder.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                if (cloudOrder != null) {
                    webTakeOrders(cloudOrder.getOrderNo());
                }
            }
        });
        this.mFloatLayout.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View paramAnonymousView, MotionEvent paramAnonymousMotionEvent) {
                FTService.this.wmParams.x = ((int) paramAnonymousMotionEvent.getRawX() - FTService.this.mFloatLayout.getMeasuredWidth() / 2);
                FTService.this.wmParams.y = ((int) paramAnonymousMotionEvent.getRawY() - FTService.this.mFloatLayout.getMeasuredHeight() / 2 - 48);
                FTService.this.mWindowManager.updateViewLayout(FTService.this.mFloatLayout, FTService.this.wmParams);
                return false;
            }
        });
    }

    public IBinder onBind(Intent paramIntent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    public void onDestroy() {
        super.onDestroy();
        onDialogDestroy();
    }

    private void onDialogDestroy() {
        stopForeground(true);
        if (mFloatLayout != null && mWindowManager != null) {
            mWindowManager.removeView(mFloatLayout);
            mFloatLayout = null;
            mWindowManager = null;
        }
        if (orderCountDownTimer != null) {
            orderCountDownTimer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {
        cloudOrder = (CloudOrder) paramIntent.getSerializableExtra("cloudOrder");
        if (cloudOrder != null) {
            tvStartAddress.setText(cloudOrder.getChufaaddress());
            tvEndAddress.setText(cloudOrder.getMudiaddress());
            tv_distance.setText(String.format("距您%s米,预估代驾费%s元", cloudOrder.getDistance(), cloudOrder.getMoney()));
            orderCountDownTimer = new OrderCountDownTimer(cloudOrder.getT() * 1000, 1000);
            orderCountDownTimer.start();
        }
        return super.onStartCommand(paramIntent, paramInt1, paramInt2);
    }

    public class OrderCountDownTimer extends CountDownTimer {
        private OrderCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (okOrder != null && cloudOrder != null) {
                okOrder.setText(String.format("接单(%ss)", millisUntilFinished / 1000L));
            }
        }

        @Override
        public void onFinish() {
            onDialogDestroy();
        }
    }

    /**
     * 接单
     */
    private void webTakeOrders(final String orderNo) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/ReceiptYunOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 接单");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null) {
                            OrderCourseActivity.show(FTService.this, orderNo);
                            onDialogDestroy();
                        } else {
                            if (rspModel.getMessage().contains("抢")) {
                                App.getInstance().showMessage(rspModel.getMessage());
                                onDialogDestroy();
                            } else if (rspModel.getMessage().contains("到期") || rspModel.getMessage().contains("无")) {
                                dialogVip();
                            } else {
                                onDialogDestroy();
                            }
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        onDialogDestroy();
                        break;
                }
            }
        });
    }

    /**
     * 拒绝订单
     */
    private void webOrderStop(String orderNo) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/driverRefuseOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
                onDialogDestroy();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                onDialogDestroy();
            }
        });
    }

    /**
     * 司机状态
     */
    private void dialogVip() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getApplication());
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("司机会员资格已到期，暂无法接单，请重新参加会员");
        builder.setNegativeButton("去参加", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                VipActivity.show(FTService.this);
                onDialogDestroy();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        final AlertDialog alertDialog=builder.create();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
            Objects.requireNonNull(alertDialog.getWindow()).setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
        } else {
            Objects.requireNonNull(alertDialog.getWindow()).setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                alertDialog.show();
            }
        });
    }

    public <T> RspModel<T> getAnalysis(AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(getClass().getSimpleName() + ":" + response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    return rspModel;
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
                break;
            default:
                App.getInstance().showMessage(getString(R.string.service_error));
                break;
        }
        return null;
    }


    private LoadingDialog loadingDialog;

    public void loadingDialogShow(final boolean canBack) {
        if (loadingDialog != null) {
            loadingDialog.cancel();
        } else {
            loadingDialog = new LoadingDialog(getApplication());
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                loadingDialog.showService(canBack, R.layout.layout_state_loading);
            }
        });

    }

    public void onDismiss() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }
}

